package com.itheima.controller;


/*
*   抽取一个基本serlet  使用uri提取方法名
* */

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

//@WebServlet("/user/*")
public class BasicSevlet extends HttpServlet {

    //使用反射抽取方法名
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取统一资源标识符
        String uri = req.getRequestURI();
        //抽取方法名
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);

        try {
            //获取方法对象
            Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //因为是私有方法 需要暴力反射
            method.setAccessible(true);
            //调用方法
            method.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
